

#include "unitscene.h"
#include "resourcemanager.h"
#include "unitfactory.h"
#include "log.h"
#include "messagequeue.h"
#include "gamemanager.h"
#include "gamedatamanager.h"
#include "CCSkeletalSprite.h"
#include "cocos-ext.h"
#include "equipmentdetaillayer.h"

static const int COLS_PER_LINE = 4;
static const int VIEW_MARGIN = 18;
static const int ITEM_WIDTH = 80;
static const int ITEM_HEIGHT = 80;
static const int ITEM_SPACE = 5;
static const int DRAGGING_OFFSET_X = 50;
static const int DRAGGING_OFFSET_Y = 50;

static float scales[] = {1.0f, 0.8f, 0.8f, 0.8f, 0.8f};

int UnitScene::attack_column1_x = 560;
int UnitScene::attack_column2_x = 630;
int UnitScene::resist_column1_x = 706;
int UnitScene::resist_column2_x = 774;
int UnitScene::first_row_y = 182;
int UnitScene::row_height = 32;
int UnitScene::label_value_space = 48;

UnitScene::UnitScene():
_layer(nullptr)
, _layerEquipmentDetail(nullptr)
, _touchPlace(UnitSceneTouchPlace::blank)
, _selectedTabIndex(0)
, _touchedTabButtonIndex(-1)
, _touchedEquipmentIndex(-1)
, _touchedUnitSlotIndex(-1)
, _draggingStartPos(CCPointZero)
, _unit(nullptr) {
	memset(_tabButtons, 0, sizeof(_tabButtons));
	memset(_unitSlots, 0, sizeof(_tabButtons));
	memset(_layerEquipments, 0, sizeof(_layerEquipments));

	_arrSprites[0] = &_arrCreatureSprites;
	_arrSprites[1] = &_arrWeaponSprites;
	_arrSprites[2] = &_arrArmorSprites;
	_arrSprites[3] = &_arrShieldSprites;
	_arrSprites[4] = &_arrSpecialSprites;
}

UnitScene::~UnitScene() {
	if (_unit) {
		delete _unit;
	}
}

bool UnitScene::init() {
	if (!CCScene::init()) {
		return false;
	}

	_layer = CCLayer::create();
	_layer->setTouchEnabled(false);
	addChild(_layer);

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
	CCSprite *spr = CCSprite::create("textures/ui_bg.png");
#else
	CCSprite *spr = CCSprite::create("textures/ui_bg.png");
#endif

	spr->setAnchorPoint(CCPointZero);

	CCSize size = spr->getContentSize();
	spr->setScaleX(GM->screenSize.width / size.width);
	spr->setScaleY(GM->screenSize.height / size.height);
	_layer->addChild(spr);

	auto btnExit = RM->makeBackButton(this, menu_selector(UnitScene::onClose), _layer, true);
	btnExit->setPosition(XY_SCALE(50, 524));

	createTabButtons();
	createEquipments();
	createUnitPad();

	cocos2d::extension::CCScale9Sprite *sprEquipmentBg = cocos2d::extension::CCScale9Sprite::create("textures/frame.png", CCRectMake(0, 0, 96, 96), CCRectMake(32, 32, 32, 32));
	sprEquipmentBg->setContentSize(CCSizeMake(X_SCALE(850), Y_SCALE(GameManager::BASE_HEIGHT)));
	sprEquipmentBg->setPosition(XY_SCALE(102, 0));
	sprEquipmentBg->setAnchorPoint(CCPointZero);
	_layer->addChild(sprEquipmentBg);

	_layerEquipmentDetail = EquipmentDetailLayer::create();
	_layerEquipmentDetail->setVisible(false);
	addChild(_layerEquipmentDetail);

	return true;
}

void UnitScene::createTabButtons() {
	int x = 102;
	int arr_y_pos[] = {439, 342, 247, 152, 54};

	for (int i = 0; i < 5; i++) {
		if (i == 0) {
			_tabButtons[i] = MAKE_SPRITE("button/round_button_1.png");
		} else {
			_tabButtons[i] = MAKE_SPRITE("button/round_button_0.png");
		}

		_tabButtons[i]->setPosition(XY_SCALE(x, arr_y_pos[i]));
		_tabButtons[i]->setAnchorPoint(ccp(1.0f, 0.5f));

		_layer->addChild(_tabButtons[i]);

		sprintf(buf, "equipment_icon_%s.png", EQUIPMENT_TYPE_NAMES[i]);
		CCSprite *spr = MAKE_SPRITE(buf);
		spr->setScale(1.0f);
		spr->setPosition(ccp(48, 48));
		_tabButtons[i]->addChild(spr);
	}
}

void UnitScene::createEquipments() {
	CCSize bgSize = CCSizeMake(X_SCALE(410), Y_SCALE(555));

	cocos2d::extension::CCScale9Sprite *sprEquipmentBg = cocos2d::extension::CCScale9Sprite::create("textures/pad_bg.png", CCRectMake(0, 0, 225, 225), CCRectMake(100, 100, 25, 25));
	sprEquipmentBg->setContentSize(bgSize);
	sprEquipmentBg->setPosition(ccp(X_SCALE(115), GM->screenSize.height / 2));
	sprEquipmentBg->setAnchorPoint(ccp(0.0f, 0.5f));
	_layer->addChild(sprEquipmentBg);

	vector<string> *arrAttrs[] = {&(GDM->creatures), &(GDM->weapons), &(GDM->armors), &(GDM->shields), &(GDM->specials)};

	for (int i = 0; i < (int) EquipmentType::count; i++) {
		int rows = arrAttrs[i]->size() / COLS_PER_LINE;
		if (arrAttrs[i]->size() % COLS_PER_LINE > 0) {
			rows++;
		}

		_DHLOG("%s, size:%d, columns: %d, rows: %d", EQUIPMENT_TYPE_NAMES[i], arrAttrs[i]->size(), COLS_PER_LINE, rows);

		CCSize size(X_SCALE((ITEM_WIDTH + ITEM_SPACE) * COLS_PER_LINE - ITEM_SPACE), Y_SCALE((ITEM_HEIGHT + ITEM_SPACE) * rows - ITEM_SPACE));
		_arrItemRows[i] = rows;

		CCSize clippingSize = CCSizeMake(size.width, bgSize.height - Y_SCALE(VIEW_MARGIN) * 2);

		CCClippingNode *clippingNode = CCClippingNode::create();
		clippingNode->setAnchorPoint(ccp(0.5f, 0.5f));
		clippingNode->setPosition(ccp(sprEquipmentBg->getPositionX() + bgSize.width / 2, sprEquipmentBg->getPositionY()));
		clippingNode->setContentSize(clippingSize);

		CCPoint vertices[] = {
				ccp(0, 0),
				ccp(clippingSize.width, 0),
				ccp(clippingSize.width, clippingSize.height),
				ccp(0, clippingSize.height)
		};

		ccColor4F black = {1, 1, 1, 1};
		CCDrawNode *stencil = CCDrawNode::create();
		stencil->drawPolygon(vertices, 4, black, 1, black);
		clippingNode->setStencil(stencil);

		_layer->addChild(clippingNode);

		CCLayer *layer = CCLayer::create();
		layer->setAnchorPoint(CCPointZero);
		layer->setContentSize(size);
		layer->setPosition(ccp(0, clippingSize.height - size.height));
		layer->setVisible(false);

		clippingNode->addChild(layer);
		_layerEquipments[i] = layer;

		int index = 0;
		float x = X_SCALE(ITEM_WIDTH / 2);
		float y = Y_SCALE(ITEM_HEIGHT / 2);
		for (auto name : *(arrAttrs[i])) {
			const EquipmentAttribute& attr = GDM->equipmentsAttribute[name];

			auto pt = ccp(x, size.height - y);

			CCSprite *itemFrame = MAKE_SPRITE("equipment_pad.png");
			itemFrame->setPosition(pt);
			layer->addChild(itemFrame);

			if (attr.rarity != EquipmentRarity::common) {
				sprintf(buf, "rarity_color_%s.png", RARITY_NAMES[(int) attr.rarity]);
				CCSprite *itemRarityBg = MAKE_SPRITE(buf);
				itemRarityBg->setPosition(ccp(itemFrame->getContentSize().width / 2, itemFrame->getContentSize().height / 2));
				itemFrame->addChild(itemRarityBg);
			}

			string iconFile = GDM->getEquipmentIconFileName((EquipmentType) i, attr.name);
			CCSprite *spr = MAKE_SPRITE(iconFile);
			spr->setScale(scales[i]);
			spr->setPosition(ccp(itemFrame->getContentSize().width / 2, itemFrame->getContentSize().height / 2));
			itemFrame->addChild(spr);

			CCSprite *sprQuantityPad = MAKE_SPRITE("quantity_pad.png");
			sprQuantityPad->setScale(1.0f);
			sprQuantityPad->setPosition(ccp(itemFrame->getContentSize().width, 0));
			sprQuantityPad->setAnchorPoint(ccp(1.0f, 0.0f));
			itemFrame->addChild(sprQuantityPad);

			sprintf(buf, "%d", GDM->equipmentsQuantity[name]);
			CCLabelTTF *labelQuantity = CCLabelTTF::create(buf, "", 12);
			labelQuantity->setPosition(ccp(sprQuantityPad->getContentSize().width / 2, sprQuantityPad->getContentSize().height / 2));
			labelQuantity->setAnchorPoint(ccp(0.5f, 0.5f));
			sprQuantityPad->addChild(labelQuantity);

			_arrSprites[i]->push_back(spr);

			x += X_SCALE(ITEM_WIDTH + ITEM_SPACE);
			index++;

			if (index > 0 && (index % COLS_PER_LINE == 0)) {
				x = X_SCALE(ITEM_WIDTH / 2);
				y += Y_SCALE(ITEM_HEIGHT + ITEM_SPACE);
			}
		}

	}

	_layerEquipments[0]->setVisible(true);

	_draggingEquipment = CCSprite::create();
	_draggingEquipment->setScale(0.5f);
	_draggingEquipment->setZOrder(100);
	_layer->addChild(_draggingEquipment);
}

void UnitScene::createUnitPad() {
	CCSize bgSize = CCSizeMake(X_SCALE(410), Y_SCALE(555));

	cocos2d::extension::CCScale9Sprite *sprUnitPadBg = cocos2d::extension::CCScale9Sprite::create("textures/pad_bg.png", CCRectMake(0, 0, 225, 225), CCRectMake(100, 100, 25, 25));
	sprUnitPadBg->setContentSize(bgSize);
	sprUnitPadBg->setPosition(ccp(X_SCALE(525), GM->screenSize.height / 2));
	sprUnitPadBg->setAnchorPoint(ccp(0.0f, 0.5f));
	_layer->addChild(sprUnitPadBg);

	auto button = RM->makeButton("button/righ_1.png", "button/righ_2.png", "button/righ_0.png", this, menu_selector(UnitScene::onSave), _layer);
	button->setPosition(XY_SCALE(855, 500));

	_unitInfo.creature = "human";
	_unit = UnitFactory::createUnit(_unitInfo, 1.0f);
	_unit->setPosition(XY_SCALE(726, 320));
	_unit->sprite->setVisible(false);
	_layer->addChild(_unit->sprite);

	CCSprite *sprPointsBg = MAKE_SPRITE("point_pad_bg.png");
	sprPointsBg->setPosition(XY_SCALE(725, 284));
	_layer->addChild(sprPointsBg);

	_labelPoints = CCLabelTTF::create("0", "", 36);
	_labelPoints->setScale(1.0f);
	_labelPoints->setPosition(ccp(sprPointsBg->getContentSize().width / 2, sprPointsBg->getContentSize().height / 2));

	sprPointsBg->addChild(_labelPoints);

	CCPoint arr_pos[] = {XY_SCALE(726, 497), XY_SCALE(600, 403), XY_SCALE(868, 403), XY_SCALE(600, 312), XY_SCALE(868, 312)};

	for (int i = 0; i < (int) EquipmentType::count; i++) {
		CCSprite *spr = MAKE_SPRITE("equipment_pad.png");
		spr->setPosition(arr_pos[i]);
		_layer->addChild(spr);

		_unitSlots[i] = spr;
	}

	CCSprite* spr = MAKE_SPRITE("unit_properties_column_header.png");
	spr->setPosition(XY_SCALE(600, 228));
	RM->makeButtonLabel("Attack", 24, spr);
	addChild(spr);

	spr = MAKE_SPRITE("unit_properties_column_header.png");
	spr->setPosition(XY_SCALE(738, 228));
	RM->makeButtonLabel("Resist", 24, spr);
	addChild(spr);

	spr = MAKE_SPRITE("unit_properties_column_header.png");
	spr->setPosition(XY_SCALE(877, 228));
	RM->makeButtonLabel("Other", 24, spr);
	addChild(spr);

	int count = (int) DamageType::count;
	for (int i = 0; i < count; i++) {
		sprintf(buf, "icon/%s.png", DAMAGE_TYPE_NAMES[i]);
		CCSprite *spr = MAKE_SPRITE(buf);
		spr->setScale(1.0f);
		_layer->addChild(spr);

		_attackValueLabels[i] = spr;

		CCLabelTTF *label = CCLabelTTF::create("0", "", 16);
		_layer->addChild(label);
		_attackValues[i] = label;

		sprintf(buf, "icon/%s.png", DAMAGE_TYPE_NAMES[i]);
		spr = MAKE_SPRITE(buf);
		spr->setScale(1.0f);
		_layer->addChild(spr);

		_resistValueLabels[i] = spr;

		label = CCLabelTTF::create("0", "", 16);
		_layer->addChild(label);
		_resistValues[i] = label;
	}

	float x = 866;
	int y = 182;
	int space = 36;

	CCSprite *sprRange = MAKE_SPRITE("icon/range.png");
	sprRange->setPosition(XY_SCALE(x, y));
	_layer->addChild(sprRange);

	_labelRange = CCLabelTTF::create("0", "", 16);
	_labelRange->setPosition(XY_SCALE(x + space, y));
	_layer->addChild(_labelRange);

	y -= row_height;
	CCSprite *sprDefense = MAKE_SPRITE("icon/defense.png");
	sprDefense->setPosition(XY_SCALE(x, y));
	_layer->addChild(sprDefense);

	_labelDefense = CCLabelTTF::create("0", "", 16);
	_labelDefense->setPosition(XY_SCALE(x + space, y));
	_layer->addChild(_labelDefense);

	y -= row_height;
	CCSprite *sprCastingTime = MAKE_SPRITE("icon/casting_time.png");
	sprCastingTime->setPosition(XY_SCALE(x, y));
	_layer->addChild(sprCastingTime);

	_labelCastingTime = CCLabelTTF::create("0", "", 16);
	_labelCastingTime->setPosition(XY_SCALE(x + space, y));
	_layer->addChild(_labelCastingTime);

	y -= row_height;
	CCSprite *sprReloadTime = MAKE_SPRITE("icon/reload_time.png");
	sprReloadTime->setPosition(XY_SCALE(x, y));
	_layer->addChild(sprReloadTime);

	_labelReloadTime = CCLabelTTF::create("0", "", 16);
	_labelReloadTime->setPosition(XY_SCALE(x + space, y));
	_layer->addChild(_labelReloadTime);


}

bool UnitScene::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) {
	if(_layerEquipmentDetail->isVisible()) {
		_layerEquipmentDetail->setVisible(false);
	}

	auto pt = pTouch->getLocation();
	for (int i = 0; i < (int) EquipmentType::count; i++) {
		if (_tabButtons[i]->hitTest(pt)) {
			_touchPlace = UnitSceneTouchPlace::tab_button;
			_touchedTabButtonIndex = i;
			break;
		}
	}

	if (_touchPlace == UnitSceneTouchPlace::blank) {
		if (_layerEquipments[_selectedTabIndex]->hitTest(pt)) {
			_touchPlace = UnitSceneTouchPlace::equipment_view;

			auto arr = _arrSprites[_selectedTabIndex];
			int index = 0;
			for (auto item : *arr) {
				if (item->hitTest(pt)) {
					_DHLOG("touched item");
					_touchPlace = UnitSceneTouchPlace::equipment_item;
					_touchedEquipmentIndex = index;
					_draggingStartPos = pt;
					break;
				}
				index++;
			}
		}
	}

	if (_touchPlace == UnitSceneTouchPlace::blank) {
		for (int i = 0; i < (int) EquipmentType::count; i++) {
			if (_unitSlots[i]->hitTest(pt)) {
				_touchPlace = UnitSceneTouchPlace::unit_slot;
				_touchedUnitSlotIndex = i;
				break;
			}
		}
	}

	return true;
}

void UnitScene::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {
	auto pt = pTouch->getLocation();
	switch (_touchPlace) {
		case UnitSceneTouchPlace::equipment_view:
			scrollEquipmentView(pTouch->getDelta().y);
	        break;
		case UnitSceneTouchPlace::equipment_item: {
			float dx = static_cast<float>(fabs(pt.x - _draggingStartPos.x));
			float dy = static_cast<float>(fabs(pt.y - _draggingStartPos.y) * 0.6f);
			_DHLOG("dx: %0.1f, dy: %0.1f", dx, dy);
			if (dx > dy) {
				_touchPlace = UnitSceneTouchPlace::dragging_equipment;

				string name = GDM->getEquipmentIconFileName((EquipmentType) _selectedTabIndex, _touchedEquipmentIndex);
				_draggingEquipment->setDisplayFrame(MAKE_SPRITEFRAME(name));
				_draggingEquipment->setScale(scales[_selectedTabIndex]);
			} else if (dy > dx) {
				_touchPlace = UnitSceneTouchPlace::equipment_view;
			}

			break;
		}
		case UnitSceneTouchPlace::dragging_equipment: {
			CCPoint localPt = _draggingEquipment->getParent()->convertToNodeSpace(pt);
			localPt.x -= X_SCALE(DRAGGING_OFFSET_X);
			localPt.y += Y_SCALE(DRAGGING_OFFSET_Y);
			_draggingEquipment->setVisible(true);
			_draggingEquipment->setPosition(localPt);

			break;
		}
		case UnitSceneTouchPlace::unit_slot: {
			if (fabs(pt.x - _draggingStartPos.x) > TOUCH_MOVE_THRESHOLD || fabs(pt.y - _draggingStartPos.y) > TOUCH_MOVE_THRESHOLD) {
				_touchPlace = UnitSceneTouchPlace::dragging_slot_equipment;

				string s = _unitInfo.getValue((EquipmentType) _touchedUnitSlotIndex);
				string name = GDM->getEquipmentIconFileName((EquipmentType) _touchedUnitSlotIndex, s);
				_draggingEquipment->setDisplayFrame(MAKE_SPRITEFRAME(name));
			}

			break;
		}
		case UnitSceneTouchPlace::dragging_slot_equipment: {
			CCPoint localPt = _draggingEquipment->getParent()->convertToNodeSpace(pt);
			_draggingEquipment->setVisible(true);
			_draggingEquipment->setPosition(localPt);

			break;
		}
		default:
			break;
	}
}

void UnitScene::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) {
	auto pt = pTouch->getLocation();

	switch (_touchPlace) {
		case UnitSceneTouchPlace::tab_button: {
			if (_tabButtons[_touchedTabButtonIndex]->hitTest(pt)) {
				switchEquipmentView();
			}

			break;
		}
		case UnitSceneTouchPlace::dragging_equipment:
			pt.x -= X_SCALE(DRAGGING_OFFSET_X);
	        pt.y += Y_SCALE(DRAGGING_OFFSET_Y);
	        handleDroppingEquipment(pt);
	        break;
		case UnitSceneTouchPlace::dragging_slot_equipment:
			handleDroppingSlotEquipment(pt);
	        break;
		case UnitSceneTouchPlace::equipment_item:
			showEquipmentDetail();
	        break;
		default:
			break;
	}

	_touchedTabButtonIndex = -1;
	_touchedEquipmentIndex = -1;
	_touchPlace = UnitSceneTouchPlace::blank;
	_DHLOG("5");
	_draggingEquipment->setVisible(false);
	_DHLOG("6");
}

void UnitScene::switchEquipmentView() {
	_tabButtons[_selectedTabIndex]->setDisplayFrame(MAKE_SPRITEFRAME("button/round_button_0.png"));
//	_tabButtons[_selectedTabIndex]->setPosition(ccp(10, _tabButtons[_selectedTabIndex]->getPositionY()));
	_layerEquipments[_selectedTabIndex]->setVisible(false);
	_selectedTabIndex = _touchedTabButtonIndex;
	_layerEquipments[_selectedTabIndex]->setVisible(true);

	_tabButtons[_selectedTabIndex]->setDisplayFrame(MAKE_SPRITEFRAME("button/round_button_1.png"));
//	_tabButtons[_selectedTabIndex]->setPosition(ccp(0, _tabButtons[_selectedTabIndex]->getPositionY()));
}

void UnitScene::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) {
	_touchedTabButtonIndex = -1;
	_touchedEquipmentIndex = -1;
	_touchPlace = UnitSceneTouchPlace::blank;
	_draggingEquipment->setVisible(false);
}

void UnitScene::onClose(CCObject *sender) {
	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
	CCDirector::sharedDirector()->popScene();
}

void UnitScene::onSave(CCObject *sender) {
	_formationInfo->units.push_back(_unitInfo);

	SEND_MSG_ARGS(MessageTarget::unit_scene, MessageTarget::formation_scene, MessageFlag::new_unit, 0);

	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
	CCDirector::sharedDirector()->popScene();
}

void UnitScene::scrollEquipmentView(float distance) {
	CCLayer *layer = _layerEquipments[_selectedTabIndex];

	CCPoint newPt = layer->getPosition();
	newPt.y += distance;

	float miny = layer->getParent()->getContentSize().height - layer->getContentSize().height;
	if (newPt.y < miny) {
		newPt.y = miny;
	}
	if (newPt.y > 0) {
		newPt.y = 0;
	}

	layer->setPosition(newPt);
}

void UnitScene::handleDroppingEquipment(const CCPoint& pt) {
	CCRect rect = CCRectMake(X_SCALE(564), Y_SCALE(274), X_SCALE(338), Y_SCALE(255));
	if (rect.containsPoint(pt)) {
		_unitSlots[_selectedTabIndex]->removeAllChildrenWithCleanup(true);

		string name = GDM->getEquipmentName((EquipmentType) _selectedTabIndex, _touchedEquipmentIndex);
		string *arr[] = {&_unitInfo.creature, &_unitInfo.weapon, &_unitInfo.armor, &_unitInfo.shield, &_unitInfo.special};
		*(arr[_selectedTabIndex]) = name;

		string iconFileName = GDM->getEquipmentIconFileName((EquipmentType) _selectedTabIndex, name);
		CCSprite *spr = MAKE_SPRITE(iconFileName);
		spr->setScale(scales[_selectedTabIndex]);
		spr->setPosition(ccp(_unitSlots[_selectedTabIndex]->getContentSize().width / 2, _unitSlots[_selectedTabIndex]->getContentSize().height / 2));

		_unitSlots[_selectedTabIndex]->addChild(spr);

		_unit->changeEquipment(_unitInfo);
		_unit->scale = getUnitScaleForIcon(_unit);
		_unit->sprite->setScale(_unit->scale);

		_unit->sprite->setVisible(true);
		if(_unit->sprite->getParent() != _layer) {
			_layer->addChild(_unit->sprite);
		}

		updateUnitAttribute();
	}
}

void UnitScene::handleDroppingSlotEquipment(const CCPoint& pt) {
	if (!_unitSlots[_touchedUnitSlotIndex]->hitTest(pt)) {
		_unitSlots[_touchedUnitSlotIndex]->removeAllChildrenWithCleanup(true);

		string *arr[] = {&_unitInfo.creature, &_unitInfo.weapon, &_unitInfo.armor, &_unitInfo.shield, &_unitInfo.special};
		*(arr[_touchedUnitSlotIndex]) = "";

		_unit->changeEquipment(_unitInfo);
		_unit->sprite->setVisible(true);
		if(_unit->sprite->getParent() != _layer) {
			_layer->addChild(_unit->sprite);
		}

		updateUnitAttribute();
	}
}

void UnitScene::setFormationInfo(FormationInfo *f) {
	_formationInfo = f;
	_unitInfo.id = _formationInfo->getUnitItemMaxID();

	sprintf(buf, "Unit%d", _unitInfo.id);
	_unitInfo.name = buf;
}

void UnitScene::updateUnitAttribute() {
	int arrAttacks[] = {
			_unit->attribute.slashAttack, // slash
			_unit->attribute.bluntAttack, // blunt
			_unit->attribute.piercingAttack, // piercing
			_unit->attribute.explosionAttack, // explosion
			_unit->attribute.fireAttack, // fire
			_unit->attribute.iceAttack, // ice
			_unit->attribute.poisonAttack, // poison
			_unit->attribute.thunderAttack, // thunder
			_unit->attribute.darkAttack, // dark
			_unit->attribute.holyAttack, // holy
	};

	int y = first_row_y;
	int n = 0;

	for(int i = 0; i < (int)DamageType::count; ++i) {
		sprintf(buf, "%d", arrAttacks[i]);
		_attackValues[i]->setString(buf);

		_attackValueLabels[i]->setVisible(arrAttacks[i] > 0);
		_attackValues[i]->setVisible(arrAttacks[i] > 0);

		if(arrAttacks[i] > 0) {
			int x = (n % 2 == 0 ? attack_column1_x : attack_column2_x);
			_attackValueLabels[i]->setPosition(ccp(x, y));
			_attackValues[i]->setPosition(ccp(x + label_value_space, y));

			if(n % 2 == 1) {
				y -= row_height;
			}

			++n;
		}
	}

	int arrResists[] = {
			_unit->attribute.slashResist, // slash
			_unit->attribute.bluntResist, // blunt
			_unit->attribute.piercingResist, // piercing
			_unit->attribute.explosionResist, // explosion
			_unit->attribute.fireResist, // fire
			_unit->attribute.iceResist, // ice
			_unit->attribute.poisonResist, // poison
			_unit->attribute.thunderResist, // thunder
			_unit->attribute.darkResist, // dark
			_unit->attribute.holyResist, // holy
	};

	y = first_row_y;
	n = 0;

	for(int i = 0; i < (int)DamageType::count; ++i) {
		sprintf(buf, "%d", arrResists[i]);
		_resistValues[i]->setString(buf);

		_resistValueLabels[i]->setVisible(arrResists[i] > 0);
		_resistValues[i]->setVisible(arrResists[i] > 0);

		if(arrResists[i] > 0) {
			int x = (n % 2 == 0 ? resist_column1_x : resist_column2_x);
			_resistValueLabels[i]->setPosition(ccp(x, y));
			_resistValues[i]->setPosition(ccp(x + label_value_space, y));

			if(n % 2 == 1) {
				y -= row_height;
			}

			++n;
		}
	}

	sprintf(buf, "%d", _unit->attribute.range);
	_labelRange->setString(buf);

	sprintf(buf, "%d", _unit->attribute.defense);
	_labelDefense->setString(buf);

	sprintf(buf, "%0d", _unit->attribute.castingTime);
	_labelCastingTime->setString(buf);

	sprintf(buf, "%0d", _unit->attribute.reloadTime);
	_labelReloadTime->setString(buf);
}

void UnitScene::keyBackClicked() {
	onClose(nullptr);
}

void UnitScene::keyMenuClicked() {

}

void UnitScene::showEquipmentDetail() {
	if (_touchedEquipmentIndex >= 0) {
		string name = GDM->getEquipmentName((EquipmentType) _selectedTabIndex, _touchedEquipmentIndex);
		const EquipmentAttribute& attr = GDM->equipmentsAttribute[name];
		_layerEquipmentDetail->setAttribute(name, attr, 0);

		CCSize size = _layerEquipmentDetail->getContentSize();
		CCSprite *sprite = (*(_arrSprites[_selectedTabIndex]))[_touchedEquipmentIndex];
		CCPoint pos = sprite->getParent()->convertToWorldSpace(sprite->getPosition());
		pos.x += ITEM_WIDTH / 2.0f * GM->minscale;
		if (pos.y > GM->screenSize.height - size.height * GM->minscale) {
			pos.y = GM->screenSize.height - size.height * GM->minscale;
		}

		_layerEquipmentDetail->setPosition(pos);
		_layerEquipmentDetail->setVisible(true);
	}
}

void UnitScene::onEnter() {
	CCScene::onEnter();

	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, -1, true);
	CCDirector::sharedDirector()->getKeypadDispatcher()->addDelegate(this);
}

void UnitScene::onExit() {
	CCScene::onExit();

	CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
	CCDirector::sharedDirector()->getKeypadDispatcher()->removeDelegate(this);
}


float UnitScene::getUnitScaleForIcon(Unit *unit) {
	float ret = 0.0f;

	if (unit->creature->genre == EquipmentGenre::artillery_3case) {
		ret = 0.6f;
	} else if (unit->creature->genre == EquipmentGenre::artillery_6case) {
		ret = 0.6f;
	} else if (unit->creature->genre == EquipmentGenre::artillery_9case) {
		ret = 0.45f;
	} else if (unit->special->genre == EquipmentGenre::special_horse || unit->special->genre == EquipmentGenre::special_boar) {
		ret = 0.6f;
	} else {
		ret = 0.6f;
	}


	return ret;
}